package com.lunwen.dao;

import com.lunwen.domain.Student;
import com.lunwen.utils.JdbcTemplate;

import java.sql.SQLException;
import java.util.List;

public class StudentDao {

    private JdbcTemplate jdbcTemplate;

    public StudentDao(){
        jdbcTemplate = JdbcTemplate.getJdbcTemplate();
    }

    //按条件查找学生
    public List<Student> find(String key){
        String sql = "select * from student where name like \"%\"?\"%\"";
        try {
            return jdbcTemplate.query(sql,Student.class,key);
        } catch (SQLException exception) {
            System.out.println(exception.toString());
            return null;
        }
    }

    //查找所有学生
    public List<Student> findAll(){
        String sql = "select * from student";
        try {
            return jdbcTemplate.query(sql,Student.class);
        } catch (SQLException exception) {
            System.out.println(exception.toString());
            return null;
        }
    }

    //新增学生
    public int insert(Student student){
        String sql = "insert into student values(?,?,?,?,?,?)";
        try {
            return jdbcTemplate.modify(sql,
                    student.getSid(),
                    student.getName(),
                    student.getMajor(),
                    student.getClazz(),
                    student.getProfessor(),
                    student.getPhone()
                    );
        } catch (SQLException exception) {
            System.out.println(exception.toString());
            return -1;
        }
    }

    //删除学生
    public int delete(String sid){
        String sql = "delete from student where sid=?";
        try {
            return jdbcTemplate.modify(sql,
                    sid
            );
        } catch (SQLException exception) {
            return -1;
        }
    }

    public static void main(String[] args) {
//        Student student = new Student("aaabbbddd","李四","计算机","计算机181","the shy","123456789");
//        System.out.println(insert(student));

//        findAll().forEach(student -> {
//            System.out.println(student.getName());
//        });

//        //删除学生
//        System.out.println(delete("aaabbbccc"));

        //关键字查询
//        find("李").forEach(temp->{
//            System.out.println(temp.getName());
//        });

    }
}
